package com.godfrey.poi.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Excel工具类
 *
 * @author godfrey
 * @since 2021-12-07
 */
public class ExcelUtil {

    /**
     * 读取Excel转为List对象
     *
     * @param pathName 文件路径名（classPath路径）
     * @param sheet    读取的sheet
     * @param entity   与Excel行对应的实体类
     * @return java.util.List
     */
    public static <T> List<T> excelToList(String pathName, String sheet, Class<T> entity) {
        List<T> list = new ArrayList<>();
        InputStream in = ExcelUtil.class.getClassLoader().getResourceAsStream(pathName);
        EasyExcel.read(in, entity, new AnalysisEventListener<T>() {
                    @Override
                    public void invoke(T eachRow, AnalysisContext analysisContext) {
                        list.add(eachRow);
                    }

                    @Override
                    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

                    }
                })
                .sheet(sheet)
                .doRead();
        return list;
    }
}